package com.ss.project.xia17user.config.security.auth2;

import com.ss.project.xia17user.dao.entity.Client;
import com.ss.project.xia17user.service.ClientService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
import org.springframework.stereotype.Component;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashSet;
import java.util.Set;

/**
 * 用户同意界面
 * @author xia17
 * @date 2021/3/26 11:01
 */
@Component
@RequiredArgsConstructor
public class UserConsentPage {

    private final ThymeleafViewResolver thymeleafViewResolver;
    private final ClientService clientService;

    private static final MediaType TEXT_HTML_UTF8 = new MediaType("text", "html", StandardCharsets.UTF_8);
    public static final String CONSENT_ACTION_PARAMETER_NAME = "consent_action";
    private static final String CONSENT_ACTION_APPROVE = "approve";
    private static final String CONSENT_ACTION_CANCEL = "cancel";

    /**
     * 显示
     * @param request /
     * @param response /
     * @param registeredClient /
     * @param authorization /
     * @throws IOException /
     */
    public void display(HttpServletRequest request, HttpServletResponse response,
                                       RegisteredClient registeredClient, OAuth2Authorization authorization) throws IOException {
        Client client = clientService.findByClientId(registeredClient.getClientId());
        // 生成html页面
        String consentPage = this.generateConsentPage(request, client, authorization);
        // 返回给浏览器
        response.setContentType(TEXT_HTML_UTF8.toString());
        response.setContentLength(consentPage.getBytes(StandardCharsets.UTF_8).length);
        response.getWriter().write(consentPage);
    }

    /**
     * 是否同意授权
     * @param request 请求信息
     * @return /
     */
    public boolean isConsentApproved(HttpServletRequest request) {
        return CONSENT_ACTION_APPROVE.equalsIgnoreCase(request.getParameter(CONSENT_ACTION_PARAMETER_NAME));
    }
    /**
     * 是否拒绝授权
     * @param request 请求信息
     * @return /
     */
    public boolean isConsentCancelled(HttpServletRequest request) {
        return CONSENT_ACTION_CANCEL.equalsIgnoreCase(request.getParameter(CONSENT_ACTION_PARAMETER_NAME));
    }

    /**
     * 生成页面
     * @param request /
     * @param client /
     * @param authorization /
     * @return /
     */
    private String generateConsentPage(HttpServletRequest request, Client client, OAuth2Authorization authorization) {
        // 参数准备
        Context context = new Context();
        // 客户端信息
        context.setVariable("clientName",client.getClientName());
        context.setVariable("clientId",client.getClientId());
        // 请求地址
        context.setVariable("actionUrl",request.getRequestURI());
        // 当前登录用户名
        context.setVariable("username",authorization.getPrincipalName());
        // state变量
        context.setVariable(OAuth2ParameterNames.STATE,authorization.getAttribute(OAuth2ParameterNames.STATE));
        // 授权范围
        OAuth2AuthorizationRequest authorizationRequest = authorization.getAttribute(
                OAuth2AuthorizationRequest.class.getName());
        assert authorizationRequest != null;
        Set<String> scopes = new HashSet<>(authorizationRequest.getScopes());
        context.setVariable("scopes",scopes);
        // 使用thymeleaf模版渲染成html 字符串
        return thymeleafViewResolver.getTemplateEngine().process("userConsent", context);
    }


}
